<?php
require_once "ModelBase.php";

class Member extends TTEvent_Table_Abstract
{
	protected $_name = 'tamtay_event_member';
	protected $_primary = array('eid', 'uid');
	
	public function getList($eid){
		$eid = (int)$eid;
		$sql = "SELECT e.*, u.uid, u.name, u.avatar, u.first_name, u.last_name, e.admin as isAdmin
				FROM users u 
				INNER JOIN tamtay_event_member e ON u.uid=e.uid
				WHERE e.eid=$eid ORDER BY e.join_date DESC";
		return $this->execSelectQuery($sql);
	}
	
	public function getGuestInvited($eid, $status, $page=0, $limit=0){
		$sql="SELECT u.uid, u.name, u.avatar, u.first_name, u.last_name 
				FROM users u
				INNER JOIN tamtay_request e ON u.uid=e.receiver_id 
				WHERE e.sender_id=? AND e.type = ? AND e.status = ?";
		$limit = (int)$limit;
		if($limit)
			$this->setRowPerPage($limit);
		$params = array($eid, REQUEST_EVENT_INVITE_TYPE, $status);
		return $this->pageQuery($sql, $params, $page);
	}
	
	
	
	public function addNewMember($eid, $uid, $isAdmin=false){
		$sql = "INSERT IGNORE INTO tamtay_event_member (eid, uid, admin, join_date) VALUES(".(int)$eid.", ".(int)$uid.", ".(int)$isAdmin.", ".(int)time().")";
		$db = $this->getMasterDB();
		$data2 = array((int)$eid, (int)$uid, (int)$isAdmin, time());
		
		//$db->query($sql, $data2);
		return $db->query($sql);
	}
	
	// need changed
	public function getFriendNotInEvent($eid, $uid){
		$sql ="SELECT u.name, u.uid, e.status, e.eid 
			FROM users u
					LEFT JOIN tamtay_event_member e ON e.uid=u.uid AND e.eid=$eid 
					LEFT JOIN tamtay_request r ON u.uid = r.receiver_id AND r.sender_id =$eid AND r.type=" . REQUEST_EVENT_INVITE_TYPE . " AND r.status = " . EVENT_INVITE_REQUEST_PENDING . "
					INNER JOIN friend f ON u.uid=f.friendID
					WHERE f.uid=$uid AND e.eid IS NULL AND r.rid IS NULL";
		return $this->execSelectQuery($sql);
	}
	
	public function getFriendInEvent($eid, $uids){
		$ret = array();
		if($eid && is_array($uids) && count($uids)>0){
			$sql="SELECT uid FROM tamtay_event_member WHERE eid=$eid AND uid IN (".implode(",", $uids).")";
			$ret = $this->execSelectQuery($sql);
		}
		return $ret;
	
	}
	
	public function getUserInvitePending($eid, $uid)
	{
		$sql="SELECT u.uid, u.name
				FROM users u INNER JOIN tamtay_request r ON u.uid=r.receiver_id 
				WHERE r.status=? AND r.sender_id=? AND r.type=? AND r.uid=?";
		$db = $this->getSlaveDB();
		$rs=$db->query($sql, array(EVENT_INVITE_REQUEST_PENDING, $eid, REQUEST_EVENT_INVITE_TYPE, $uid));
		$data=array();
		while ($obj=$rs->fetch())
		{
			$data[]=$obj;
		}
		return $data;
	}
	
	public function removePending($eid, $uid, $eventUid){
		$sql = "DELETE FROM tamtay_request WHERE sender_id=? AND receiver_id=? AND status=? AND type=? AND uid=?";
		$db = $this->getMasterDB();
		$db->query($sql, array($eid, $uid, EVENT_INVITE_REQUEST_PENDING, REQUEST_EVENT_INVITE_TYPE, $eventUid));
	}

	public function addPending($eid, $uid, $eventAdminUid){
		$sql="SELECT COUNT(*) FROM tamtay_request WHERE sender_id=$eid AND receiver_id=$uid AND type=" . REQUEST_EVENT_INVITE_TYPE;
		$db = $this->getSlaveDB();
		
		$c = $db->fetchOne($sql);
		if ($c==0)
		{
			$dbMaster = $this->getMasterDB();
			$sql="INSERT INTO tamtay_request (sender_id, receiver_id, created, status, type, message, uid) VALUES (?, ?, ?, ?, ?, ?, ?)";
			$dbMaster->query($sql, array($eid, $uid, time(), EVENT_INVITE_REQUEST_PENDING, REQUEST_EVENT_INVITE_TYPE, '', $eventAdminUid));
			return 1;
		}
		return 0;
	}
	
	public function sendInvite($eid, $uid, $msg){
		
		if ($eid==0)
		{
			return;
		}
		
		$effect_sql = "SELECT receiver_id FROM tamtay_request WHERE sender_id=? AND uid=? AND status=? AND type=?";
		
		$db = $this->getSlaveDB();
		$rs = $db->query($effect_sql, array($eid, $uid, EVENT_INVITE_REQUEST_PENDING, REQUEST_EVENT_INVITE_TYPE));
		
		$uids = array();
		while($receiver = $rs->fetch()){
			$uids[] = $receiver->receiver_id;
		}
		$total_row_effect = count($uids);
		
		$updateSql = "UPDATE tamtay_request SET status=?, message=? WHERE sender_id=? AND uid=? AND status=? AND type=?";
		$dbMaster = $this->getMasterDB();
		$dbMaster->query($updateSql, array(EVENT_INVITE_REQUEST_SENT, $dbMaster->quote($msg), $eid, $uid, EVENT_INVITE_REQUEST_PENDING, REQUEST_EVENT_INVITE_TYPE));
		
		$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_SENT, $total_row_effect);
		
		// update user statistic
		for($i=0; $i<$total_row_effect; $i++){
			$this->updateUserStatistic($uids[$i], REQUEST_EVENT_INVITE_TYPE);
		}
		return $uids;
	}
	
	
	public function changeMemberCount($eid, $type, $status, $num){
		if($num==0) return;
		$count_field = $this->getCountFieldName($type, $status);
		
		
		if($count_field != ""){
			$sql = "UPDATE tamtay_event SET $count_field=$count_field".($num>=0?"+$num":"-".abs($num))." WHERE eid=$eid".($num<0?" AND $count_field>=".abs($num):"");
			$dbMaster = $this->getMasterDB();
			$dbMaster->query($sql);
		}
	}
    
    public function updateMemberCount($eid, $type, $status){
                                    
         $dbMaster = $this->getMasterDB();
        //update event member count
        if($type=="" && ($status="member" || $status="admin")){
            $sql = "SELECT COUNT(*) FROM tamtay_event_member WHERE eid=".$eid;
            $total = $dbMaster->fetchOne($sql);
            $sqlUpdate = "UPDATE tamtay_event SET member_count = ? WHERE eid=?";
            $dbMaster->query($sqlUpdate, array($total, $eid));
        }
            
        else if($type == REQUEST_EVENT_INVITE_TYPE){
            switch($status){
                case EVENT_INVITE_REQUEST_SENT:
                    $sql = "SELECT COUNT(*) FROM tamtay_request WHERE sender_id=".$eid." AND type=".REQUEST_EVENT_INVITE_TYPE." AND status=".EVENT_INVITE_REQUEST_SENT;
                    $total = $dbMaster->fetchOne($sql);
                    $sqlUpdate = "UPDATE tamtay_event SET guest_not_read_count = ? WHERE eid=?";
                    $dbMaster->query($sqlUpdate, array($total, $eid));
                    break;
                case EVENT_INVITE_REQUEST_MAYBE_ATTENDING:
                    $sql = "SELECT COUNT(*) FROM tamtay_request WHERE sender_id=".$eid." AND type=".REQUEST_EVENT_INVITE_TYPE." AND status=".EVENT_INVITE_REQUEST_MAYBE_ATTENDING;
                    $total = $dbMaster->fetchOne($sql);
                    $sqlUpdate = "UPDATE tamtay_event SET guest_maybe_attending_count = ? WHERE eid=?";
                    $dbMaster->query($sqlUpdate, array($total, $eid));
                    break;
                case EVENT_INVITE_REQUEST_NOT_ATTENDING:
                    $sql = "SELECT COUNT(*) FROM tamtay_request WHERE sender_id=".$eid." AND type=".REQUEST_EVENT_INVITE_TYPE." AND status=".EVENT_INVITE_REQUEST_NOT_ATTENDING;
                    $total = $dbMaster->fetchOne($sql);
                    $sqlUpdate = "UPDATE tamtay_event SET guest_not_attending_count = ? WHERE eid=?";
                    $dbMaster->query($sqlUpdate, array($total, $eid));
                    break;
            }
        }
        else if($type == REQUEST_EVENT_REQUEST_TYPE){
            $count_field = "request_count";
            $sql = "SELECT COUNT(*) FROM tamtay_request WHERE receiver_id=".$eid." AND type=".REQUEST_EVENT_REQUEST_TYPE;
            $total = $dbMaster->fetchOne($sql);
            $sqlUpdate = "UPDATE tamtay_event SET request_count = ? WHERE eid=?";
            $dbMaster->query($sqlUpdate, array($total, $eid));
        }
    }
	
	
	
	private function updateUserStatistic($uid, $type="", $status=""){
		$count_field = "";
		if($type=="" && ($status="member" || $status="admin")){
			
			$count_field = "count_event";	// is member
			
			$sql = "SELECT COUNT(*) FROM tamtay_event_member WHERE uid=?";
			
			$db = $this->getMasterDB();
			$event_count = $db->fetchOne($sql, $uid);
			
			$updateSql = "UPDATE statistic SET $count_field=? WHERE uid=?";
			return $db->query($updateSql, array($event_count, $uid));
		}
		
		else if($type == REQUEST_EVENT_INVITE_TYPE){
			
			$count_field = "count_event_invite";
			$sql = "SELECT COUNT(*) FROM tamtay_request WHERE receiver_id=? AND type=? AND status=?";
			
			$db = $this->getMasterDB();
			$invite_count = $db->fetchOne($sql, array($uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_SENT));
			
			$updateSql = "UPDATE statistic SET $count_field=? WHERE uid=?";
			return $db->query($updateSql, array($invite_count, $uid));
		}
		
		else if($type == REQUEST_EVENT_REQUEST_TYPE){
			
			$count_field = "count_event_request";
			$sql = "SELECT COUNT(*) FROM tamtay_request WHERE sender_id=? AND type=?";
			
			$db = $this->getMasterDB();
			$request_count = $db->fetchOne($sql, array($uid, REQUEST_EVENT_REQUEST_TYPE));
			
			$updateSql = "UPDATE statistic SET $count_field=? WHERE uid=?";
			return $db->query($updateSql, array($request_count, $uid));
		}
		return false;
	}
	
	private function getCountFieldName($type="", $status=""){
		$count_field = "";
		if($type=="" && ($status="member" || $status="admin"))
			$count_field = "member_count";	// is member
		if($type == REQUEST_EVENT_INVITE_TYPE){
			switch($status){
				case EVENT_INVITE_REQUEST_SENT:
					$count_field = "guest_not_read_count";	// sent and not yet decided by receiver
					break;
				case EVENT_INVITE_REQUEST_MAYBE_ATTENDING:
					$count_field = "guest_maybe_attending_count";	// sent and not yet decided by receiver
					break;
				case EVENT_INVITE_REQUEST_NOT_ATTENDING:
					$count_field = "guest_not_attending_count";	// sent and not yet decided by receiver
					break;
			}
		}
		else if($type == REQUEST_EVENT_REQUEST_TYPE){
			$count_field = "request_count";
		}
		return $count_field;
	}
	
	public function getMemberStatus($eid, $uid){
		$memsarr = array();
		$memsarr['isAdmin'] = 0;
		$memsarr['isMember'] = 0;
		$memsarr['isMaybe'] = 0;
		$memsarr['isNot'] = 0;
		$memsarr['isInvited'] = 0;
		$memsarr['isRequest'] = 0;
		
		if($uid <= 0 || !is_numeric($uid))
			return 0;
		$where = " WHERE ";
		if(is_numeric($eid))
			$where .= "e.eid=$eid";
		else
			$where .= "e.eid IN ($eid)";
		
		$sql = "SELECT DISTINCT e.eid, IF(em.admin>0,1,0) AS admin, " .
				"IF(em.eid>0,1,0) AS member, " .
				"IF(r2.receiver_id>0,1,0) AS w_request, " .
				"IF(r1.status=".EVENT_INVITE_REQUEST_SENT.",1,0) AS w_invite, " .
				"IF(r1.status=".EVENT_INVITE_REQUEST_MAYBE_ATTENDING.",1,0) AS maybe_att, " .
				"IF(r1.status=".EVENT_INVITE_REQUEST_NOT_ATTENDING.",1,0) AS not_att " .
				" FROM tamtay_event e 
				  LEFT JOIN tamtay_event_member em ON e.eid=em.eid AND em.uid=$uid " .
				" LEFT JOIN tamtay_request r1 ON e.eid=r1.sender_id AND r1.receiver_id=$uid  AND r1.type=".REQUEST_EVENT_INVITE_TYPE." " .
				" LEFT JOIN tamtay_request r2 ON e.eid=r2.receiver_id AND r2.sender_id=$uid  AND r2.type=".REQUEST_EVENT_REQUEST_TYPE." " .
				$where;
		
		$db = $this->getSlaveDB();
		$result = $db->query($sql);
		$ret = array();
			
		while ($event_status = $result->fetch()){
			$statusArr = $memsarr;
			
			if($event_status->member==1){
				$statusArr['isMember'] = 1;
				if($event_status->admin==1){
					$statusArr['isAdmin'] = 1;
				}
			}
			else if($event_status->w_invite==1){
				$statusArr['isInvited'] = 1;
			}
			else if($event_status->maybe_att==1){
				$statusArr['isMaybe'] = 1;
			}
			else if($event_status->not_att==1){
				$statusArr['isNot'] = 1;
			}
			else if($event_status->w_request==1){
				$statusArr['isRequest'] = 1;
			}
				
			$ret[$event_status->eid]=$statusArr;
		}
		if(is_numeric($eid))
			$ret = $ret[$eid];
		return $ret;
	}
	
	public function memberNewStatus($eid, $uid, $newStatus, $needInsert=true){
		
		switch($newStatus){
			case EVENT_USER_STATUS_ADMIN:
			case EVENT_USER_STATUS_MEMBER:
				$am = $this->addNewMember($eid, $uid);
				if($am){
					//$this->changeMemberCount($eid, "", "member", 1);
                    $this->updateMemberCount($eid, "", "member");
					$this->updateUserStatistic($uid,  "", "member");
					/*
					$userList = myttevent_get_user_list($uid);
					$eventList = myttevent_get_event_list($eid);
					$feedObj = myttevent_make_feed_object($eventList[$eid], $userList[$uid]);
					myttevent_add_feed(NEWSFEED_EVENT_JOIN, $feedObj);
					*/
				}
				$this->clearUserRequest($eid, $uid);
				break;
			case EVENT_USER_STATUS_REQUEST:
				$ir = $this->insertRequest($eid, $uid, REQUEST_EVENT_REQUEST_TYPE, 0);
				if($ir){
					$this->changeMemberCount($eid, REQUEST_EVENT_REQUEST_TYPE, "", 1);
					$this->updateUserStatistic($uid, REQUEST_EVENT_REQUEST_TYPE);
				}
				break;
			case EVENT_USER_STATUS_INVITED:
				$ir = false;
				if($needInsert)
					$ir = $this->insertRequest($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_SENT);
				else
					$ir = $this->updateRequestStatus($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_SENT);
					
				if($ir){
					$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_SENT, 1);
					$this->updateUserStatistic($uid, REQUEST_EVENT_INVITE_TYPE);
				}
				break;
			case EVENT_USER_STATUS_MAYBE:
				$ir = false;
				if($needInsert)
					$ir = $this->insertRequest($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_MAYBE_ATTENDING);
				else
					$ir = $this->updateRequestStatus($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_MAYBE_ATTENDING);
				if($ir){
					$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_MAYBE_ATTENDING, 1);
					$this->updateUserStatistic($uid, REQUEST_EVENT_INVITE_TYPE);
				}
				break;
			case EVENT_USER_STATUS_NOT:
				$ir = false;
				if($needInsert)
					$ir = $this->insertRequest($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_NOT_ATTENDING);
				else
					$ir = $this->updateRequestStatus($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_NOT_ATTENDING);
				
				if($ir){
					$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_NOT_ATTENDING, 1);
					$this->updateUserStatistic($uid, REQUEST_EVENT_INVITE_TYPE);
				}
				break;
		}
	}
	
	/**
	 * return 1: need 
	 * 
	 * */
	public function removeMemberStatus($eid, $uid, $oldStatus){
		$ret = 0;
		switch($oldStatus){
			case EVENT_USER_STATUS_ADMIN:
			case EVENT_USER_STATUS_MEMBER:
				$this->leaveEvent($uid, $eid);
				//$this->changeMemberCount($eid, REQUEST_EVENT_REQUEST_TYPE, "", 0-$row_effect);
				$ret = 1;
				break;
			case EVENT_USER_STATUS_REQUEST:
				$row_effect = $this->removeRequestInvite($eid, $uid, REQUEST_EVENT_REQUEST_TYPE);
				$this->changeMemberCount($eid, REQUEST_EVENT_REQUEST_TYPE, "", 0-$row_effect);
				$this->updateUserStatistic($uid, REQUEST_EVENT_REQUEST_TYPE);
				break;
			case EVENT_USER_STATUS_INVITED:
				$row_effect = $this->removeRequestInvite($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_SENT);
				$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_SENT, 0-$row_effect);
				$this->updateUserStatistic($uid, REQUEST_EVENT_INVITE_TYPE);
				break;
			case EVENT_USER_STATUS_MAYBE:
				$row_effect = $this->removeRequestInvite($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_MAYBE_ATTENDING);
				$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_MAYBE_ATTENDING, 0-$row_effect);
				$this->updateUserStatistic($uid, REQUEST_EVENT_INVITE_TYPE);
				break;
			case EVENT_USER_STATUS_NOT:
				$row_effect = $this->removeRequestInvite($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_NOT_ATTENDING);
				$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_NOT_ATTENDING, 0-$row_effect);
				$this->updateUserStatistic($uid, REQUEST_EVENT_INVITE_TYPE);
				break;
		}
		return $ret;
	}
	
	//leave a event
	public function leaveEvent($uid, $eid){
	
		$rm = $this->removeMember($eid, $uid);
		if($rm){
			//$this->changeMemberCount($eid, "", "member", -1);
            $this->updateMemberCount($eid, "", "member");
			$this->updateUserStatistic($uid, "", "member");
			/*
			if($feedObj==""){
				$userList = myttevent_get_user_list($uid);
				$eventList = myttevent_get_event_list($eid); 
				$feedObj = myttevent_make_feed_object($eventList[$eid], $userList[$uid]);
			}
			myttevent_add_feed(NEWSFEED_EVENT_LEAVE, $feedObj);
			*/
		}

	}
	
	
	private function removeRequestInvite($eid, $uid, $type, $status=""){
		return $this->deleteRequest($eid, $uid, $type, $status);
	}
	
	private function deleteRequest($eid, $uid, $type, $status=""){
		//
		$status_cond = "";
		if($type==REQUEST_EVENT_INVITE_TYPE){
			$sender_id = $eid;
			$receiver_id = $uid;
			if($status != "")
				$status_cond = " AND status=$status";
		}
		else if($type==REQUEST_EVENT_REQUEST_TYPE){
			$sender_id = $uid;
			$receiver_id = $eid;
		}
		
		$db = $this->getMasterDB();
		
		$effect_str = "SELECT COUNT(*) FROM tamtay_request WHERE sender_id=$sender_id AND receiver_id=$receiver_id AND type=$type $status_cond";
		$row_effect = $db->fetchOne($effect_str);
		
		$db->query("DELETE FROM tamtay_request WHERE sender_id=? AND receiver_id=? AND type=? $status_cond", array($sender_id, $receiver_id, $type));
		return $row_effect;
	}
	
	
	// remove all request when event is removed
	function removeAllRequest($sender_id=0, $receiver_id=0, $type, $status=0){
		if($type != REQUEST_EVENT_INVITE_TYPE && $type != REQUEST_EVENT_REQUEST_TYPE)
			return 1;
		if($type==REQUEST_EVENT_INVITE_TYPE && $sender_id==0)
			return 1;
		if($type==REQUEST_EVENT_REQUEST_TYPE && $receiver_id==0)
			return 1;
		
		$where_arr = array();
		if($sender_id != 0)
			$where_arr[] = "sender_id=$sender_id";
		if($receiver_id != 0)
			$where_arr[] = "receiver_id=$receiver_id";
		$where_arr[] = "type=$type";
		if($status != 0)
			$where_arr[] = "status=$status";
		$where = "";
		foreach($where_arr as $condition){
			if($where == "")
				$where .= " WHERE $condition";
			else
				$where .= " AND $condition";
		}
		$db = $this->getMasterDB();
		$rows_sql = "SELECT COUNT(*) FROM  tamtay_request $where";
		$total_row_effect = $db->fetchOne($rows_sql);
		$db->query("DELETE FROM tamtay_request $where");
		return $total_row_effect;
	}
	
	public function clearUserRequest($eid, $uid){
		$not_reply = $this->removeAllRequest($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_SENT);
		$maybe_attending = $this->removeAllRequest($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_MAYBE_ATTENDING);
		$not_attending = $this->removeAllRequest($eid, $uid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_NOT_ATTENDING);
		
		$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_SENT, 0-$not_reply);
		$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_MAYBE_ATTENDING, 0-$maybe_attending);
		$this->changeMemberCount($eid, REQUEST_EVENT_INVITE_TYPE, EVENT_INVITE_REQUEST_NOT_ATTENDING, 0-$not_attending);
		
		$this->updateUserStatistic($uid, REQUEST_EVENT_INVITE_TYPE);
		
		$this->removeAllRequest($eid, $uid, REQUEST_EVENT_INVITE_TYPE);
	}
	
	public function insertRequest($eid, $uid, $type, $new_status=0){
		$sql="INSERT INTO tamtay_request (sender_id, receiver_id, created, status, type, uid) VALUES (?, ?, ?, ?, ?, ?)";
		if($type==REQUEST_EVENT_INVITE_TYPE){
			$sender_id = $eid;
			$receiver_id = $uid;
		}
		else if($type==REQUEST_EVENT_REQUEST_TYPE){
			$sender_id = $uid;
			$receiver_id = $eid;
		}
		
		$db = $this->getMasterDB();
		return $db->query($sql, array($sender_id, $receiver_id, time(), $new_status, $type, $uid));
	}
	
	public function updateRequestStatus($eid, $uid, $type, $new_status=0){
		$sender_id = 0;
		$receiver_id = 0;
		$sql="UPDATE tamtay_request SET  status=? WHERE sender_id=? AND receiver_id=? AND type=?";
		if($type==REQUEST_EVENT_INVITE_TYPE){
			$sender_id = $eid;
			$receiver_id = $uid;
		}
		else if($type==REQUEST_EVENT_REQUEST_TYPE){
			$sender_id = $uid;
			$receiver_id = $eid;
		}
		else{
			return false;
		}
		
		$db = $this->getMasterDB();
		return $db->query($sql, array($new_status, $sender_id, $receiver_id, $type));
	}
	
	
	
	public function removeAllEventRequest($eid){
		$sql = "DELETE FROM tamtay_request WHERE (sender_id=? AND type=?) OR (receiver_id=? AND type=?)";
		$db = $this->getMasterDB();
		$db->query($sql, array($eid, REQUEST_EVENT_INVITE_TYPE, $eid, REQUEST_EVENT_REQUEST_TYPE));
	}
	
	public function removeAllEventMember($eid){
		$sql = "DELETE FROM tamtay_event_member WHERE eid=?";
		$db = $this->getMasterDB();
		$db->query($sql, $eid);
	}
	
	public function isWaitingAcceptRequest($eid, $uid){
		$uid = (int)$uid;
		$eid = (int)$eid;
		if($uid <= 0)
			return false;
			
		$sql="SELECT sender_id FROM tamtay_request WHERE sender_id=? AND receiver_id=? AND type=?";
		
		$db = $this->getSlaveDB();
		$rs = $db->fetchOne($sql, array($uid, $eid, REQUEST_EVENT_REQUEST_TYPE));
		return ($rs>0);
	}
	
	//get the list of requesting users
	public function getRequestList($eid, $page=0, $limit=20)
	{
		$limit = (int)$limit;
		$eid = (int)$eid;
		$sql="SELECT u.uid, u.name, u.avatar, u.first_name, u.last_name
				FROM users u
				INNER JOIN tamtay_request r ON u.uid=r.uid AND r.receiver_id=$eid AND r.type=" . REQUEST_EVENT_REQUEST_TYPE . "
				ORDER BY r.created DESC";
		$sql_count="SELECT count(u.uid)
				FROM users u 	INNER JOIN tamtay_request r ON u.uid=r.uid AND r.receiver_id=$eid AND r.type=" . REQUEST_EVENT_REQUEST_TYPE;
		
		if($limit)
			$this->setRowPerPage($limit);
		//$params = array($eid, REQUEST_EVENT_INVITE_TYPE);
		return $this->pageQuery($sql, "", $page, $sql_count);
	}
	
	
//get the list of requesting and invited uid
	public function getRequestInvitedUids($eid)
	{
		$eid = (int)$eid;
		$sql="SELECT sender_id, receiver_id
				FROM  tamtay_request 
				WHERE (receiver_id=$eid AND type=" . REQUEST_EVENT_REQUEST_TYPE . ")
				OR (sender_id=$eid AND type=" . REQUEST_EVENT_INVITE_TYPE . " AND status<>".EVENT_INVITE_REQUEST_NOT_ATTENDING.")";
		
		$db = $this->getSlaveDB();
		$rs = $db->query($sql, $eid);
		$ret = array();
		while($row = $rs->fetch()){
			if($row->sender_id == $eid)
				$ret[] = $row->receiver_id;
			else
				$ret[] = $row->sender_id;
		}
		return $ret;
	}
	
	public function getMemberList($eid, $page=0, $limit=20){
		$limit = (int)$limit;
		$eid = (int)$eid;
		$page = (int)$page;
		$sql="SELECT m.*, u.name, u.avatar, u.first_name, u.last_name, m.admin as isAdmin FROM tamtay_event_member m 
					INNER JOIN users u ON m.uid=u.uid
					WHERE m.eid=$eid";
		
		if($limit)
			$this->setRowPerPage($limit);
		//$params = array($eid, REQUEST_EVENT_INVITE_TYPE);
		return $this->pageQuery($sql, "", $page);
	}
	
	public function getUserInfo($uid){
		$uid = (int)$uid;
		if(!$uid)
			return false;
		$sql = "SELECT * FROM users WHERE uid=?";
		$db = $this->getSlaveDB();
		$rs = $db->query($sql, $uid);
		$ret = $rs->fetch();
		return $ret;
	}
	
	public function makeAdmin($eid, $uid){
		$eid = (int)$eid;
		$uid = (int)$uid;
		$ret = false;
		if($eid && $uid){
			$sql = "UPDATE tamtay_event_member SET admin=1 WHERE eid=? AND uid=?";
			$db = $this->getMasterDB();
			$ret = $db->query($sql, array($eid, $uid));
		}
		return $ret;
	}
	
	public function removeAdmin($eid, $uid){
		$eid = (int)$eid;
		$uid = (int)$uid;
		$ret = false;
		if($eid && $uid){
			$sql = "UPDATE tamtay_event_member SET admin=0 WHERE eid=? AND uid=?";
			$db = $this->getMasterDB();
			$ret = $db->query($sql, array($eid, $uid));
		}
		return $ret;
	}
	
	public function removeMember($eid, $uid){
		$eid = (int)$eid;
		$uid = (int)$uid;
		$ret = false;
		if($eid && $uid){
			$sql = "DELETE FROM tamtay_event_member WHERE eid=? AND uid=?";
			$db = $this->getMasterDB();
			$ret = $db->query($sql, array($eid, $uid));
		}
		return $ret;
	}
    //va
    public function getTimeLine($eid){
        $sql="SELECT m.uid,count(m.uid) as n, FROM_DAYS(ceil(join_date/(24*60*60)) + 719527 ) as day FROM tamtay_event_member m INNER JOIN users u ON m.uid=u.uid  WHERE m.eid=? GROUP BY day ORDER BY day DESC";
        $db = $this->getMasterDB();
        return $db->fetchAll($sql, array($eid));
    }
    
    public function getEventMemberInfo($eid,$action){
        $db = $this->getMasterDB();
        if($action=="min max"){
            $sql="SELECT MIN(join_date) as min,MAX(join_date) as max FROM tamtay_event_member where eid=? AND join_date!=0";       
        }
        return $db->fetchAll($sql, array($eid));  
    }
    public function getNumMember($eid,$t1,$t2){
        $sql="SELECT count(*) as n from tamtay_event_member WHERE eid=? AND join_date>=? AND join_date<=?";
        $db = $this->getMasterDB();
        return $db->fetchOne($sql, array($eid,$t1,$t2));
    }
    //va
    
}

